package com.levis.huolalarobber.service;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.GestureDescription;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.graphics.Path;
import android.graphics.Rect;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import com.levis.huolalarobber.Constant;
import com.levis.huolalarobber.utils.SPutils;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class HuolalaAccessibilityService extends AccessibilityService {
    final static String TAG = "---XyS---";
    //tv_status_date 訂單時間ID
    //iv_distance 距離ID
    //v_station_point 地址前圓點ID
    //tv_station_address 地址ID
    //fl_label 車類型佈局ID

    //下單頁面ID
    //tvPricePaidByHuolala已支付
    //tvPricePaidByClient向客戶收取
    //toolbar頂部導航欄

    private boolean isScrolled = false;//已經滑動過一次了

    private String lastAddress;
    private String topActivityPackageName;
    private Timer pickUpTimer;
    private TimerTask loopPikcUpTask;


    @Override
    protected void onServiceConnected() {
        Log.i(TAG, "config success!");
    }


    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        // TODO Auto-generated method stub
        int eventType = event.getEventType();
        if (eventType == AccessibilityEvent.TYPE_WINDOWS_CHANGED) {
            Log.d(TAG, "TYPE_WINDOWS_CHANGED" + eventType);
        } else if (eventType == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED) {
            //新訂單，界面發生變化
            if ((boolean) SPutils.get(this, Constant.SP_OPEN, false))
                toEnterFirst(event);
        } else if (eventType == AccessibilityEvent.TYPE_VIEW_CLICKED) {
            //確認了搶單要做的
            haveClickPickUp(event);
        } else if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
            topActivityPackageName = event.getClassName().toString();
            //搶單界面，滑動搶單
            toScrollButton(event);
        }

    }

    //判斷是否在要搶單的價格內，如果不在要搶的價格那麼直接返回
    private boolean judgePriceNotPickUp(AccessibilityNodeInfo nodeInfo) {
        String minPrice = (String) SPutils.get(getApplicationContext(), Constant.SP_MIN_PRICE, "0.00".toString());
        String maxPrice = (String) SPutils.get(getApplicationContext(), Constant.SP_MAX_PRICE, "9999.99".toString());
        float allCount = 0;
        //向平台收款
        List<AccessibilityNodeInfo> huolalaPrice = nodeInfo
                .findAccessibilityNodeInfosByViewId("com.lalamove.huolala.driver:id/tvPricePaidByHuolala");
        if (huolalaPrice.size() > 0) {
            String price = huolalaPrice.get(0).getText().toString();
            if (price.length() > 2) {
                String count = price.substring(1, price.length());
                allCount = allCount + Float.valueOf(count);
            }
        }
        //向用户收款
        List<AccessibilityNodeInfo> clientPrice = nodeInfo
                .findAccessibilityNodeInfosByViewId("com.lalamove.huolala.driver:id/tvPricePaidByClient");
        if (clientPrice.size() > 0) {
            String price = clientPrice.get(0).getText().toString();
            if (price.length() > 2) {
                String count = price.substring(1, price.length());
                allCount = allCount + Float.valueOf(count);
            }
        }
        //判断价格区间
        if (allCount < Float.valueOf(minPrice) || allCount > Float.valueOf(maxPrice)) {
            return true;
        } else {
            return false;
        }
    }

    private void toScrollButton(final AccessibilityEvent event) {
        if (isScrolled) return;
        if ("com.lalamove.huolala.OrderDetailActivity".equals(event.getClassName())) {
            final AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
            if (nodeInfo == null) {
                Log.d(TAG, "nodeInfo null");
                return;
            }
            if ((boolean) SPutils.get(getApplicationContext(), Constant.SP_OPEN_PRICE, false)) {
                if (judgePriceNotPickUp(nodeInfo)) {
                    //不在價格範圍內，那麼直接返回列表界面，不滑動搶單
                    List<AccessibilityNodeInfo> topBars = nodeInfo
                            .findAccessibilityNodeInfosByViewId("com.lalamove.huolala.driver:id/toolbar");
                    if (topBars.size() > 0) {
                        AccessibilityNodeInfo topBar = topBars.get(0);
                        for (int i = 0; i < topBar.getChildCount(); i++) {
                            if (topBar.getChild(i).getClassName().toString().equals("android.widget.ImageButton")) {
                                topBar.getChild(i).performAction(AccessibilityNodeInfo.ACTION_CLICK);
                            }
                        }
                    }
                    return;
                }
            }
            List<AccessibilityNodeInfo> scrollBtn = nodeInfo
                    .findAccessibilityNodeInfosByViewId("com.lalamove.huolala.driver:id/btnPositive");
            if (scrollBtn.size() > 0) {
                AccessibilityNodeInfo view = scrollBtn.get(0);
                Rect bounds = new Rect();
                view.getBoundsInScreen(bounds);
                Path path = new Path();
                path.moveTo(bounds.left, bounds.top);
                path.lineTo(bounds.right, bounds.bottom);
                GestureDescription.Builder builder = new GestureDescription.Builder();
                final GestureDescription gestureDescription = builder.addStroke(new GestureDescription.StrokeDescription(path, 100, 500)).build();
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        dispatchGesture(gestureDescription, new GestureResultCallback() {
                            @Override
                            public void onCompleted(GestureDescription gestureDescription) {
                                isScrolled = true;
                                //滑動完成，進行確定點擊
                                doPickUp();
                                super.onCompleted(gestureDescription);
                            }

                            @Override
                            public void onCancelled(GestureDescription gestureDescription) {
                                super.onCancelled(gestureDescription);
                            }
                        }, null);
                    }
                }, 200);
            }
        } else {
            isScrolled = false;
        }
    }

//    //模擬點擊事件
//    private void performClickOrSlide(AccessibilityNodeInfo view) {
//        Rect bounds = new Rect();
//        view.getBoundsInScreen(bounds);
//        Path path = new Path();
//        path.moveTo(bounds.left, bounds.top);
//        path.lineTo(bounds.right, bounds.bottom);
//        GestureDescription.Builder builder = new GestureDescription.Builder();
//        final GestureDescription gestureDescription = builder.addStroke(new GestureDescription.StrokeDescription(path, 100, 800)).build();
//        dispatchGesture(gestureDescription, new GestureResultCallback() {
//            @Override
//            public void onCompleted(GestureDescription gestureDescription) {
//                view.performAction(AccessibilityNodeInfo.ACTION_CLICK);
//                super.onCompleted(gestureDescription);
//            }
//
//            @Override
//            public void onCancelled(GestureDescription gestureDescription) {
//                view.performAction(AccessibilityNodeInfo.ACTION_CLICK);
//                super.onCancelled(gestureDescription);
//            }
//        }, null);
//    }

    //btn_pickup
    private void doPickUp() {
        if ("com.lalamove.huolala.dialog.OrderRemarkDialog".equals(topActivityPackageName) || "com.lalamove.huolala.customview.HllProgressDialog".equals(topActivityPackageName)) {
            final AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
            if (nodeInfo == null) {
                Log.d(TAG, "nodeInfo null");
                return;
            }
            final List<AccessibilityNodeInfo> pickUpBtn = nodeInfo
                    .findAccessibilityNodeInfosByViewId("com.lalamove.huolala.driver:id/btn_pickup");
            SPutils.put(getApplicationContext(), "btnSize", "" + pickUpBtn.size());
            if (pickUpBtn.size() > 0) {
//                loopPikcUpTask = new TimerTask() {
//                    public void run() {

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        AccessibilityNodeInfo view = pickUpBtn.get(0);
                        Rect bounds = new Rect();
                        view.getBoundsInScreen(bounds);
                        Path path = new Path();
                        path.moveTo(bounds.left, bounds.top);
                        path.lineTo(bounds.right, bounds.bottom);
                        GestureDescription.Builder builder = new GestureDescription.Builder();
                        SPutils.put(getApplicationContext(), "doScrollTouch", "Done");
                        final GestureDescription gestureDescription = builder.addStroke(new GestureDescription.StrokeDescription(path, 100, 500)).build();
                        dispatchGesture(gestureDescription, new GestureResultCallback() {
                            @Override
                            public void onCompleted(GestureDescription gestureDescription) {
                                super.onCompleted(gestureDescription);
                            }

                            @Override
                            public void onCancelled(GestureDescription gestureDescription) {
                                super.onCancelled(gestureDescription);
                            }
                        }, null);
                    }
                },5000);
//                if (pickUpBtn.get(0).isClickable()) {
//
//                }
//                    }
//                };
//                pickUpTimer = new Timer();
//                pickUpTimer.schedule(loopPikcUpTask, 100);
            }
        }
    }

    private void haveClickPickUp(AccessibilityEvent event) {
        if (event.getText().toString().contains("确认抢单")) {
            SPutils.put(getApplicationContext(), "haveClickPickUpDone", "Done");
            if (pickUpTimer != null) {
                pickUpTimer.cancel();
                pickUpTimer.purge();
                pickUpTimer = null;
            }
            if (loopPikcUpTask != null) {
                loopPikcUpTask.cancel();
                loopPikcUpTask = null;
            }
        }
    }

    private void toEnterFirst(AccessibilityEvent event) {
        if ("com.lalamove.huolala.driver.HomeActivity"
                .equals(topActivityPackageName)) {
            isScrolled = false;
            AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
            if (nodeInfo == null) {
                return;
            }
//            List<AccessibilityNodeInfo> remarkTv = nodeInfo
//                    .findAccessibilityNodeInfosByViewId("com.lalamove.huolala.driver:id/tvRemark");
//            if (remarkTv.size() > 0) {
//                for (int i = 0; i < remarkTv.size(); i++) {
//                    if (remarkTv.get(i).getText().toString().contains("需要拆空调")) {
//                        remarkTv.get(i).getParent().performAction(AccessibilityNodeInfo.ACTION_CLICK);
//                    }
//                }
//            }


            String nowAddress = "";
            List<AccessibilityNodeInfo> AddressTv = nodeInfo
                    .findAccessibilityNodeInfosByViewId("com.lalamove.huolala.driver:id/tv_station_address");
            if (AddressTv.size() > 0) {
                nowAddress = AddressTv.get(0).getText().toString();
            }
            if (!TextUtils.isEmpty(lastAddress)) {
                if (nowAddress.equals(lastAddress)) {
                    return;
                }
            }
            List<AccessibilityNodeInfo> firstItem = nodeInfo
                    .findAccessibilityNodeInfosByViewId("com.lalamove.huolala.driver:id/rl_price");

            if (firstItem.size() > 0) {
//            此處無法獲取價格
//               for(int i=0;i<firstItem.size();i++){
//                   AccessibilityNodeInfo priceLayout= firstItem.get(i);
//               }
                firstItem.get(0).getParent().performAction(AccessibilityNodeInfo.ACTION_CLICK);
            }
            lastAddress = nowAddress;
        }

    }


    private boolean isTopActivity() {
        boolean isTop = false;
        ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
//        Log.d(TAG, "isTopActivity = " + cn.getClassName());
        if (cn.getClassName().contains("com.lalamove.huolala.driver")) {
            isTop = true;
        }
        return isTop;
    }

    @Override
    public void onInterrupt() {
        // TODO Auto-generated method stub
    }

    private void playAlarm() {
        try {
            MediaPlayer mp = new MediaPlayer();
            mp.setDataSource(this, RingtoneManager
                    .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
            mp.prepare();
            mp.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
